import { createRouter, createWebHashHistory, RouteRecordRaw, RouteLocationNormalized } from 'vue-router';
import cache from '@/utils/cache';

let router:any = null;
const routes:RouteRecordRaw[] = [
    {
        path:'/home',
        redirect:'/',
        component:() => import('@/views/home/index.vue')
    },
    {
        path:'/',
        name:'home',
        component:() => import('@/views/home/index.vue'),
        meta:{ title:'主页', keepAlive:true }
    },
    {
        path:'/login',
        name:'login',
        component:() => import('@/views/login/index.vue'),
        meta:{ title:'登陆', keepAlive:false }
    }
];

router = createRouter({
    history: createWebHashHistory(),
    routes
});

type Route = RouteLocationNormalized;
// 全局前置路由守卫
router.beforeEach((to:Route, from:Route, next:any):void =>
{
    let flag = cache.token.get() && cache.userData.get();
    if (flag)
    {
        if (to.path === '/login')
        {
            next('/');
        }
        else
        {
            next();
        }
    }
    else
    {
        if (to.path === '/login')
        {
            next();
        }
        else
        {
            next('/login');
        }
    }
});

// 全局后置路由守卫
router.afterEach((to:Route) =>
{
    document.title = to.meta.title + '- 小鹏桌面' || '小鹏桌面';
});

export default router;
